/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modelasimu;

import animacion.cola;
import animacion.salida;
import animacion.servidor;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Javier Cifuentes M
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        DefaultTableModel modelo = (DefaultTableModel) servidoresTabla.getModel();
        modelo.setRowCount(0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tasaLlegada = new javax.swing.JTextField();
        startSimulacion = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        unidadSeleccionada = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        infinitaCheck = new javax.swing.JCheckBox();
        truncadaCola = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        servidoresTabla = new javax.swing.JTable();
        addServidor = new javax.swing.JButton();
        removeLastServidor = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        tiempoSimulacion = new javax.swing.JTextField();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("Simulador:");

        jLabel2.setText("Tasa de Llegada:");

        startSimulacion.setText("Iniciar");
        startSimulacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startSimulacionActionPerformed(evt);
            }
        });

        jLabel6.setText("Unidades:");

        unidadSeleccionada.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Clientes/Hora", "Clientes/Minuto", "Clientes/Segundo" }));

        jLabel3.setText("Servidores y Tasa Servicio:");

        jLabel4.setText("Cola:");

        infinitaCheck.setText("infinita");
        infinitaCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                infinitaCheckActionPerformed(evt);
            }
        });

        servidoresTabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Id", "Tasa(Clientes/Segundo)"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(servidoresTabla);

        addServidor.setText("Agregar");
        addServidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addServidorActionPerformed(evt);
            }
        });

        removeLastServidor.setText("Quitar ultimo");
        removeLastServidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeLastServidorActionPerformed(evt);
            }
        });

        jLabel5.setText("Tiempo de Simulacion (segundos):");

        tiempoSimulacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tiempoSimulacionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(startSimulacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(unidadSeleccionada, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(tasaLlegada))
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(truncadaCola, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(infinitaCheck))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(tiempoSimulacion, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(removeLastServidor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(addServidor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(unidadSeleccionada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tasaLlegada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(truncadaCola, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(infinitaCheck))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addServidor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeLastServidor))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(tiempoSimulacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(startSimulacion)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void infinitaCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infinitaCheckActionPerformed
        // TODO add your handling code here:
        if (infinitaCheck.isSelected()) {
            truncadaCola.setEnabled(false);
        } else {
            truncadaCola.setEnabled(true);
        }
    }//GEN-LAST:event_infinitaCheckActionPerformed

    private void addServidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addServidorActionPerformed
        // TODO add your handling code here:
        DefaultTableModel modelo = (DefaultTableModel) servidoresTabla.getModel();
        int id = modelo.getRowCount() + 1;
        askTasaAtencion tasa = new askTasaAtencion(this, true);
        tasa.showDialog();
        double val = tasa.Aceptar();
        System.out.println("VALOR" + val);
        if (val > 0) {
            modelo.addRow(new Object[]{id, val});
        }
        System.out.println("R:" + modelo.getRowCount());
    }//GEN-LAST:event_addServidorActionPerformed

    private void removeLastServidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeLastServidorActionPerformed
        // TODO add your handling code here:
        DefaultTableModel modelo = (DefaultTableModel) servidoresTabla.getModel();
        if (modelo.getRowCount() > 0) {
            int id = modelo.getRowCount();
            modelo.setRowCount(id - 1);
        }
    }//GEN-LAST:event_removeLastServidorActionPerformed

    private void startSimulacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startSimulacionActionPerformed
        // TODO add your handling code here:
        //tasa de llegada

        int sel = unidadSeleccionada.getSelectedIndex();
        boolean continuar = true;
        Double tasallegada = -1.0;
        boolean truncado = false;
        int truncamiento = 0;
        double tiempo = 0;
        String txt = tasaLlegada.getText();
        try {
            tasallegada = Double.parseDouble(txt);
            if (tasallegada < 0) {
                JOptionPane.showMessageDialog(this, "Por favor especifique una tasa de llegada valida", "Error", JOptionPane.ERROR_MESSAGE);
                continuar = false;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Por favor especifique una tasa de llegada valida", "Error", JOptionPane.ERROR_MESSAGE);
            continuar = false;
        }
        //cola
        if (infinitaCheck.isSelected()) {
            truncado = false;
            truncamiento = 0;
        } else {
            truncado = true;
            txt = truncadaCola.getText();
            try {
                truncamiento = Integer.parseInt(txt);
                if (truncamiento < 0) {
                    JOptionPane.showMessageDialog(this, "Por favor especifique un truncamiento de cola correcto", "Error", JOptionPane.ERROR_MESSAGE);
                    continuar = false;
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Por favor especifique un truncamiento de cola correcto", "Error", JOptionPane.ERROR_MESSAGE);
                continuar = false;
            }
        }
        //tiempo de simulacion
        txt = tiempoSimulacion.getText();
        try {
            tiempo = Double.parseDouble(txt);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Por favor especifique un tiempo de simulacion correcto", "Error", JOptionPane.ERROR_MESSAGE);
            continuar = false;
        }
        //servidores
        salida S = new salida();
        cola C = new cola(truncado,truncamiento);
        DefaultTableModel modelo = (DefaultTableModel) servidoresTabla.getModel();
        LinkedList<servidor> servidores = new LinkedList<servidor>();
        if (modelo.getRowCount() > 0) {
            for (int i = 0; i < modelo.getRowCount(); i++) {
                String tasa = modelo.getValueAt(i, 1).toString();
                String id = modelo.getValueAt(i, 0).toString();
                Double tasaatencion = Double.parseDouble(tasa);
                servidor s = new servidor(i,0,tasaatencion,C,S);
                servidores.add(s);
            }
        } else {
            continuar = false;
            JOptionPane.showMessageDialog(this, "Por favor especifique al menos un servidor", "Error", JOptionPane.ERROR_MESSAGE);
        }
        //unidades
        if (continuar) {
            switch (sel) {
                case 0://hora
                    //clientes/hr *1hr/60 min * 1 min/60 seg
                    tasallegada = (tasallegada / 3600);
                    break;
                case 1://minuto
                    //clientes/min * 1 min/60 seg
                    tasallegada = (tasallegada / 60);
                    break;
            }
            SimWindow sw = new SimWindow(tasallegada, servidores, tiempo,C,S);
            sw.setVisible(true);
            this.dispose();
        }

    }//GEN-LAST:event_startSimulacionActionPerformed

    private void tiempoSimulacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tiempoSimulacionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tiempoSimulacionActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addServidor;
    private javax.swing.JCheckBox infinitaCheck;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton removeLastServidor;
    private javax.swing.JTable servidoresTabla;
    private javax.swing.JButton startSimulacion;
    private javax.swing.JTextField tasaLlegada;
    private javax.swing.JTextField tiempoSimulacion;
    private javax.swing.JTextField truncadaCola;
    private javax.swing.JComboBox unidadSeleccionada;
    // End of variables declaration//GEN-END:variables
}
